const fs = require('fs');
const path = require('path');
const BaseIpcHandler = require('../BaseIpcHandler');

class DeleteDatasetHandler extends BaseIpcHandler {
    async handle(event, params) {
        // 解析参数
        // console.log('>> DeleteDatasetHandler params = ', params);
        const { dataset_id } = params;

        // 业务逻辑
        let result = null;
        try {
            // 删除数据库中的记录
            await this.app.db.datasets.deleteDataset(dataset_id);
            await this.app.db.categories.deleteCategoriesByIdList([dataset_id]);

            // 关闭list.db文件
            let list_db = this.app.list_dbs[dataset_id];
            list_db && (await list_db.close());
            this.app.list_dbs[dataset_id] = null;

            // 删除dataset对应的缓存数据目录
            let userDataPath = this.app.userDataPath;
            const datasetTmpDir = path.join(userDataPath, 'datasets', dataset_id.toString());
            if (fs.existsSync(datasetTmpDir)) {
                fs.rmSync(datasetTmpDir, { recursive: true });
            }
            // console.log(`## Dataset with ID ${dataset_id} Deleted OK!`);
            result = { code: 0, msg: 'Delete Dataset OK!' };
        } catch (err) {
            console.error(`Error delete dataset ${dataset_id}`, err);
            result = { code: -1, msg: err.message };
        }

        // 返回结果
        if (event.from === 'localserver') {
            event.resp.send(result);
        } else {
            return result;
        }
    }
}

module.exports = DeleteDatasetHandler;
